from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox
from PyQt5.QtCore import pyqtSlot
import sqlite3
from PyQt5.QtCore import Qt


class LoginDialog(QDialog):
    def __init__(self, parent=None):
        super(LoginDialog, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.setWindowTitle('登录')
        layout = QVBoxLayout()
        # 设置窗口的位置和大小
        self.setGeometry(300, 300, 500, 500)



        label_welcome = QLabel('欢迎使用 图像识别系统')
        label_welcome.setAlignment(Qt.AlignCenter)
        layout.addWidget(label_welcome)

        self.label_username = QLabel('用户名:')
        self.line_username = QLineEdit()
        layout.addWidget(self.label_username)
        layout.addWidget(self.line_username)

        self.label_password = QLabel('密码:')
        self.line_password = QLineEdit()
        self.line_password.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.label_password)
        layout.addWidget(self.line_password)

        self.btn_login = QPushButton('登录')
        self.btn_login.clicked.connect(self.on_login)
        layout.addWidget(self.btn_login)

        self.btn_register = QPushButton('注册')
        self.btn_register.clicked.connect(self.on_register)
        layout.addWidget(self.btn_register)

        self.btn_cancel = QPushButton('取消')
        self.btn_cancel.clicked.connect(self.reject)
        layout.addWidget(self.btn_cancel)


        label_welcome.setStyleSheet(
            " color:white;"
            "font-size: 40px; "
            "font-weight: bold;")

        self.label_username.setStyleSheet(
            " color:white;")

        self.label_password.setStyleSheet(
            " color:white;")

        # 设置窗口背景图片
        pixmap = QPixmap("../exampleimage/background.png")
        self.setStyleSheet(
            f"background-image: url({'../exampleimage/background.png'}); background-repeat: no-repeat; background-position: center;")

        # self.btn_login.setStyleSheet(
        #    "QPushButton{color:black}"
        #  "QPushButton:hover{color:red}"
        #  "QPushButton{background-color:rgb(78,255,255)}"
        #  "QPushButton{border:2px}"
        #  "QPushButton{border-radius:10px}"
        #  "QPushButton{padding:2px 4px}"
        # )
        self.btn_login.setStyleSheet("""
            background-color: blue;
            color: yellow;
            border: 2px solid black;
            font-size: 16px;
            padding: 10px;
            width: 150px;
            height: 50px;
        """)
        self.btn_register.setStyleSheet(
            """
                        background-color: blue;
                        color: yellow;
                        border: 2px solid black;
                        font-size: 16px;
                        padding: 10px;
                        width: 150px;
                        height: 50px;
                    """

        )

        self.btn_cancel.setStyleSheet(
            """
                        background-color: blue;
                        color: yellow;
                        border: 2px solid black;
                        font-size: 16px;
                        padding: 10px;
                        width: 150px;
                        height: 50px;
                    """

        )

        self.setLayout(layout)


    @pyqtSlot()
    def on_register(self):
        username = self.line_username.text()
        password = self.line_password.text()
        if self.register_user(username, password):
            QMessageBox.information(self, '成功', '注册成功！')
        else:
            QMessageBox.warning(self, '错误', '注册失败！')

    def register_user(self, username, password):
        # 连接到SQLite数据库（如果不存在则创建）  
        conn = sqlite3.connect('../code/users.db')
        cursor = conn.cursor()

        # 创建表（如果表不存在）  
        cursor.execute('''CREATE TABLE IF NOT EXISTS users  
                          (username TEXT PRIMARY KEY, password TEXT)''')

        # 插入新用户  
        try:
            cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password))
            conn.commit()
            # 查询并打印表的内容  
            cursor.execute("SELECT * FROM users")
            rows = cursor.fetchall()  # 获取所有查询结果  
            for row in rows:
                print(row)
            return True
        except sqlite3.IntegrityError:
            # 如果用户名已存在，则不插入  
            QMessageBox.warning(self, '错误', '用户名已存在！')
            return False
        finally:
            conn.close()

    @pyqtSlot()
    def on_login(self):
        username = self.line_username.text()
        password = self.line_password.text()
        if self.validate_credentials(username, password):
            self.accept()
        else:
            QMessageBox.warning(self, '错误', '用户名或密码错误！')

    def validate_credentials(self, username, password):
        conn = sqlite3.connect('../code/users.db')
        cursor = conn.cursor()

        # 查询数据库中的用户  
        cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password))
        user = cursor.fetchone()

        # 关闭数据库连接  
        conn.close()

        # 如果找到了用户，返回 True；否则返回 False  
        return user is not None
